import java.util.*;

public class PaperList {
    private final String teacher;
    private final List<Paper> papers;
    private final PaperSelection selections;

    public PaperList(String teacher, List<Paper> papers) {
        this.teacher = teacher;
        this.papers = new ArrayList<>(papers); // 防御性拷贝
        this.selections = new PaperSelection();
    }

    // 基于随机策略选择论文
    public List<Paper> selectPaperByRandom(Student student) throws NoEnoughPapersException {
        if (student == null) {
            throw new IllegalArgumentException("学生参数不能为空");
        }
        
        // 检查学生是否已选择论文（根据前置条件）
        for (Map.Entry<Paper, Student> entry : selections.getSelections().entrySet()) {
            if (entry.getValue().equals(student)) {
                throw new IllegalStateException("学生 " + student.getName() + " 已选择过论文");
            }
        }

        PaperType preferredType = student.getPreferredPaperType();
        List<Paper> availablePapers = getUnselectedPapersByType(preferredType);
        int q = student.getPreferredQuantity();

        if (q <= 0) {
            throw new IllegalArgumentException("学生期望选择的论文数量必须大于0");
        }

        if (availablePapers.size() < q) {
            throw new NoEnoughPapersException(student.getName(), q, availablePapers.size());
        }

        List<Paper> selected = randomSelectPapers(availablePapers, q);
        for (Paper paper : selected) {
            selections.addSelection(student, paper);
        }
        return Collections.unmodifiableList(selected);
    }

    // 私有辅助方法：随机选择论文
    private List<Paper> randomSelectPapers(List<Paper> available, int quantity) {
        List<Paper> result = new ArrayList<>(available);
        Collections.shuffle(result);
        return result.subList(0, quantity);
    }

    // 获取未被选择的论文
    public List<Paper> getUnselectedPapersByType(PaperType type) {
        List<Paper> results = new ArrayList<>();
        for (Paper paper : papers) {
            if (!selections.isSelected(paper) && 
                (type == PaperType.Any || 
                 (paper instanceof Thesis && type == PaperType.Thesis) || 
                 (paper instanceof ConferencePaper && type == PaperType.ConferencePaper) || 
                 (paper instanceof JournalPaper && type == PaperType.JournalPaper))) {
                results.add(paper);
            }
        }
        return Collections.unmodifiableList(results);
    }

    // 获取选择结果
    public PaperSelection getSelectionResult() {
        return selections;
    }
}    